/**
 * $File: TT_Graphics.cpp
 * $Synopsis: Graphics Stuff Implementation
 * $Author: Ted Yin (ymfoi)
 * $Version: alpha 1.0
 * $Date: Sat Nov 27 23:07:43 2010 CST
 */

#include "TT_Graphics.h"
#include "../Logic/TT_Logic.h"

using namespace TT_Graphics;
using namespace TT_Logic;

/////////////////////////// Draw ////////////////////////
void Starting_Draw();
void Playing_Draw();
void Menu_Draw();

void Draw() {

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	
	Game_State_Ptr -> Draw();	

	glutSwapBuffers();
	glFlush();

}

/////////////////////////// Draw ////////////////////////

/////////////////////////// Idle ////////////////////////

void Idle() {

	static char buff[50];

		

	static int LastUpdate = 0,LF = 0;
	static int frames = 0;
	
	int CurrentTime = glutGet(GLUT_ELAPSED_TIME);
	//if (frames == FPS) usleep(1000*(1000 - (CurrentTime - LastUpdate)));
	frames++;
	double dt = (CurrentTime - LF) / 10.0;
		Game_State_Ptr -> Idle(dt);
		glutPostRedisplay();
		LF = CurrentTime;

	if ((CurrentTime - LastUpdate) >= 1000)
	{
		sprintf(buff,"FPS: %d\n",frames);
		frames = 0;
		LastUpdate = CurrentTime;
	glutSetWindowTitle(buff);
	}


}
/////////////////////////// Idle ////////////////////////



/////////////////////////// Init ////////////////////////
void Init() {

	glClearColor(0.0,0.0,0.0,0.0);
	glShadeModel(GL_FLAT);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_LINE_SMOOTH);
	glEnable(GL_POINT_SMOOTH);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

}


/////////////////////////// Init ////////////////////////

/////////////////////////// Event ////////////////////////

void Reshape(int Height,int Width) {

	glViewport(0,0,Height,Width);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(45.0f,2,0.1,5000);
}

void TT_Graphics::RunGame(int argc,char **argv) {

	srand(time(0));

	TT_Logic::Init();	
	Game_State_Ptr -> Init();
	glutInit(&argc,argv);
	glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
	glutInitWindowPosition(0,0);
	glutInitWindowSize(1000,500);
	glutCreateWindow("T-Tron Test");
	glutFullScreen();

	::Init();
	glutDisplayFunc(Draw);
	glutIdleFunc(::Idle);
	glutReshapeFunc(Reshape);
	glutKeyboardFunc(TT_Trigger::Keyboard_Event);
	glutSpecialFunc(TT_Trigger::Special_Keyboard_Event);
	glutMainLoop();

}
